package com.hydra.base.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.FatalBeanException;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Supplier;

/**
 * Bean转换工具
 * @Author Hydra
 * @Date 2022/5/1 22:30
 */
public class BeanConvertUtils extends BeanUtils {

    /**
     * 从Map集合中复制属性到对象中
     * @param source    集合
     * @param target    目标对象
     */
    public static void copyMapToBean(Map<String, Object> source, Object target){
        copyMapToBean(source, target, null);
    }

    /**
     * 从Map集合中复制属性到对象中
     * 下划线转驼峰
     * @param source    集合
     * @param target    目标对象
     */
    public static void copyMapToBeanConvertKey(Map<String, Object> source, Object target){
        copyMapToBean(source, target, StringUtil::underLineToCamel);
    }

    //从Map集合中复制属性到对象中
    public static void copyMapToBean(Map<String, Object> source, Object target, KeyConvertor convertor){
        if(source == null || target == null){
            return;
        }
        Class<?> targetClass = target.getClass();
        Set<String> keySet = source.keySet();
        for (String key : keySet) {
            Object value = source.get(key);
            //转换一下key的名称，例如下划线转驼峰
            if(convertor != null){
                key = convertor.convertKey(key);
            }
            PropertyDescriptor targetPd = getPropertyDescriptor(targetClass, key);
            if(targetPd == null || targetPd.getReadMethod() == null) {
                continue;
            }
            try {
                // 这里判断以下value是否为空
                if (value != null) {
                    Class<?> propertyType = targetPd.getPropertyType();
                    value = FormatUtil.formatValueByType(value, propertyType);
                    Method writeMethod = targetPd.getWriteMethod();
                    if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                        writeMethod.setAccessible(true);
                    }
                    writeMethod.invoke(target, value);
                }
            } catch (Exception ex) {
                throw new FatalBeanException("Could not copy properties from source to target", ex);
            }

        }

    }

    /**
     * bean copy不复制null值
     * @param source    源对象
     * @param target    目标对象
     */
    public static void copyPropertiesWithoutNull(Object source, Object target) {
        if(source == null || target == null){
            return;
        }
        Class<?> tClass = target.getClass();
        Class<?> sourceClass = source.getClass();
        PropertyDescriptor[] targetPds = getPropertyDescriptors(tClass);
        for (PropertyDescriptor targetPd : targetPds) {
            if(targetPd.getWriteMethod() == null) {
                continue;
            }
            PropertyDescriptor sourcePd = getPropertyDescriptor(sourceClass, targetPd.getName());
            if(sourcePd == null || sourcePd.getReadMethod() == null) {
                continue;
            }
            try {
                Method readMethod = sourcePd.getReadMethod();
                if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                    readMethod.setAccessible(true);
                }
                Object value = readMethod.invoke(source);
                // 这里判断以下value是否为空
                if (value != null) {
                    Method writeMethod = targetPd.getWriteMethod();
                    if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
                        writeMethod.setAccessible(true);
                    }
                    writeMethod.invoke(target, value);
                }
            } catch (Exception ex) {
                throw new FatalBeanException("Could not copy properties from source to target", ex);
            }
        }
    }


    /**
     * 转换对象
     *
     * @param source         源对象
     * @param targetSupplier 目标对象供应方
     * @param callBack       回调方法
     * @param <S>            源对象类型
     * @param <T>            目标对象类型
     * @return 目标对象
     */
    public static <S, T> T convertTo(S source, Supplier<T> targetSupplier, ConvertCallBack<S, T> callBack) {
        if (null == source || null == targetSupplier) {
            return null;
        }

        T target = targetSupplier.get();
        copyProperties(source, target);
        if (callBack != null) {
            callBack.callBack(source, target);
        }
        return target;
    }

    public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier) {
        return convertListTo(sources, targetSupplier, null);
    }

    /**
     * 转换对象
     *
     * @param sources        源对象list
     * @param targetSupplier 目标对象供应方
     * @param callBack       回调方法
     * @param <S>            源对象类型
     * @param <T>            目标对象类型
     * @return 目标对象list
     */
    public static <S, T> List<T> convertListTo(List<S> sources, Supplier<T> targetSupplier, ConvertCallBack<S, T> callBack) {
        if (null == sources || null == targetSupplier) {
            return null;
        }

        List<T> list = new ArrayList<>(sources.size());
        for (S source : sources) {
            T target = targetSupplier.get();
            copyProperties(source, target);
            if (callBack != null) {
                callBack.callBack(source, target);
            }
            list.add(target);
        }
        return list;
    }

    /**
     * 回调接口
     *
     * @param <S> 源对象类型
     * @param <T> 目标对象类型
     */
    @FunctionalInterface
    public interface ConvertCallBack<S, T> {
        void callBack(S t, T s);
    }

    /**
     * 转换集合的回调接口
     */
    @FunctionalInterface
    public interface KeyConvertor {
        String convertKey(String key);
    }
}
